import React, { useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import './App.css';
import Login from './pages/Login';
import Register from './pages/Register';
import DashboardLayout from './components/DashboardLayout';
import Dashboard from './pages/Dashboard';
import UserVehicleDashboard from './pages/UserVehicleDashboard';
import DataClassification from './pages/DataClassification';
import EmergencyAlerts from './pages/EmergencyAlerts';
import TrackHistory from './pages/TrackHistory';
import PublicData from './pages/PublicData';
import VehicleNetworking from './pages/VehicleNetworking';
import AdminDashboard from './pages/AdminDashboard';
import VehicleList from './pages/VehicleList';
import AddVehicle from './pages/AddVehicle';
import ReportMaintenance from './pages/ReportMaintenance';
import MyMaintenanceRecords from './pages/MyMaintenanceRecords';
import ServiceProviderMaintenance from './pages/ServiceProviderMaintenance';
import VehicleDetail from './pages/VehicleDetail';
import VehicleEdit from './pages/VehicleEdit';
import ServiceProviderAttributes from './pages/ServiceProviderAttributes';
import ServiceProviderUserFiles from './pages/ServiceProviderUserFiles';
import ServiceProviderInfoDisplay from './pages/ServiceProviderInfoDisplay';
import { setupAuthInterceptor, setupResponseInterceptor } from './utils/api';

// 增强的路由守卫组件
const ProtectedRoute = ({ children, requiredRole }) => {
  const token = localStorage.getItem('token');
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  
  // 检查token是否存在且不为空
  if (!token || token === 'undefined' || token === 'null') {
    // 清除可能存在的无效token
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    return <Navigate to="/login" replace />;
  }
  
  // 检查角色权限
  if (requiredRole) {
    if (requiredRole === 'ADMIN' && userInfo.role !== 'ADMIN') {
      return <Navigate to="/" replace />;
    }
    if (requiredRole === 'USER' && userInfo.role !== 'USER') {
      return <Navigate to="/" replace />;
    }
    if (requiredRole === 'SERVICE_PROVIDER' && userInfo.role !== 'SERVICE_PROVIDER') {
      return <Navigate to="/" replace />;
    }
  }
  
  return children;
};

// 内部应用组件，用于使用useNavigate hook
const AppContent = () => {
  const navigate = useNavigate();
  
  useEffect(() => {
    // 设置授权拦截器，确保所有API请求都包含token
    const removeAuthInterceptor = setupAuthInterceptor();
    
    // 设置响应拦截器，处理401等错误
    const removeResponseInterceptor = setupResponseInterceptor(navigate);
    
    // 组件卸载时移除拦截器
    return () => {
      removeAuthInterceptor();
      removeResponseInterceptor();
    };
  }, [navigate]);
  
  return (
    <div className="App">
      <Routes>
        {/* 公共路由 */}
        <Route path="/login" element={<Login />} />
        <Route path="/register" element={<Register />} />
        
        {/* 管理员路由 */}
        <Route path="/admin" element={
          <ProtectedRoute requiredRole="ADMIN">
            <DashboardLayout />
          </ProtectedRoute>
        }>
          <Route path="dashboard" element={<AdminDashboard />} />
        </Route>
        
        {/* 服务商路由 */}
        <Route path="/service-provider" element={
          <ProtectedRoute requiredRole="SERVICE_PROVIDER">
            <DashboardLayout />
          </ProtectedRoute>
        }>
          <Route index element={<Navigate to="attributes" replace />} />
          <Route path="attributes" element={<ServiceProviderAttributes />} />
          <Route path="user-files" element={<ServiceProviderUserFiles />} />
          <Route path="info-display" element={<ServiceProviderInfoDisplay />} />
          {/* 移除可能导致冲突的通用路由路径 */}
        </Route>

        {/* 普通用户路由 */}
        <Route path="/" element={
          <ProtectedRoute>
            <DashboardLayout />
          </ProtectedRoute>
        }>
          <Route index element={<UserVehicleDashboard />} />
          <Route path="dashboard" element={<UserVehicleDashboard />} />
          <Route path="vehicles" element={<VehicleList />} />
          <Route path="vehicles/add" element={<AddVehicle />} />
          <Route path="vehicles/:id" element={<VehicleDetail />} />
<Route path="vehicles/detail/:id" element={<VehicleDetail />} />
          <Route path="vehicles/:id/edit" element={<VehicleEdit />} />
          <Route path="vehicle-data" element={<DataClassification />} />
          <Route path="track-history" element={<TrackHistory />} />
          <Route path="public-data" element={<PublicData />} />
          <Route path="vehicle-networking" element={<VehicleNetworking />} />
          <Route path="emergency-alerts" element={<EmergencyAlerts />} />
        </Route>
        
        {/* 维修记录相关路由 */}
        <Route path="/report-maintenance" element={
          <ProtectedRoute>
            <DashboardLayout />
          </ProtectedRoute>
        }>
          <Route index element={<ReportMaintenance />} />
        </Route>
        
        <Route path="/maintenance-records" element={
          <ProtectedRoute>
            <DashboardLayout />
          </ProtectedRoute>
        }>
          <Route index element={<MyMaintenanceRecords />} />
        </Route>
        
        <Route path="/service-provider/maintenance" element={
          <ProtectedRoute requiredRole="SERVICE_PROVIDER">
            <DashboardLayout />
          </ProtectedRoute>
        }>
          <Route index element={<ServiceProviderMaintenance />} />
        </Route>
        
        {/* 重定向所有其他路径到登录页 */}
        <Route path="*" element={<Navigate to="/login" replace />} />
      </Routes>
    </div>
  );
};

function App() {
  return (
    <Router>
      <AppContent />
    </Router>
  );
}

export default App;
